package cn.wolfcode.wolf2w.service.impl;


import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.StrategyTheme;
import cn.wolfcode.wolf2w.query.DestinationQuery;
import cn.wolfcode.wolf2w.query.StrategyThemeQuery;
import cn.wolfcode.wolf2w.repository.StrategyThemeRepository;
import cn.wolfcode.wolf2w.service.IStrategyThemeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Optional;

@Service
public class StrategyThemeServiceImpl implements IStrategyThemeService {
    @Autowired
    private StrategyThemeRepository strategyThemeRepository;
    @Autowired
    private MongoTemplate template;

    @Override
    public void insert(StrategyTheme strategyTheme) {
        strategyTheme.setId(null);
        strategyThemeRepository.save(strategyTheme);
    }

    @Override
    public void delete(String id) {
        strategyThemeRepository.deleteById(id);
    }

    @Override
    public void update(StrategyTheme strategyTheme) {
        strategyThemeRepository.save(strategyTheme);
    }

    @Override
    public StrategyTheme findById(String id) {
        Optional<StrategyTheme> strategyTheme = strategyThemeRepository.findById(id);
        return strategyTheme.orElse(null);
    }

    @Override
    public List<StrategyTheme> findAll() {
        List<StrategyTheme> all = strategyThemeRepository.findAll();
        return all;
    }

    @Override
    public Page<StrategyTheme> query(StrategyThemeQuery qo, String parentId) {
        Query query = new Query();

        if (StringUtils.hasText(parentId)){
            query.addCriteria(Criteria.where("parentId").is(parentId));
        }else {
            query.addCriteria(Criteria.where("parentId").is(null));
        }

        if (StringUtils.hasText(qo.getKeyword())){
            query.addCriteria(Criteria.where("name").regex(qo.getKeyword()));
        }
        long total = template.count(query, Destination.class);
        if (total == 0){
            return Page.empty();
        }
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),Sort.Direction.ASC, "_id");
        query.with(pageable);
        List<StrategyTheme> list = template.find(query, StrategyTheme.class);
        return new PageImpl<>(list, pageable,total);

    }

    @Override
    public List findByState() {
        List<StrategyTheme> strategyTheme = strategyThemeRepository.findByState(0);
        return strategyTheme;
    }


}
